﻿using System.Collections.Generic;
using System.Data;
using System.Text;

namespace SqlExecHelper.Query
{
        internal class SqlUnionRow : ISqlBasic
        {
                private readonly ISqlBasic[] _QueryList = null;
                private readonly string _OrderBy = null;
                private readonly string[] _Columns;
                public SqlUnionRow(ISqlBasic[] query, string[] columns, string orderBy)
                {
                        this._Columns = columns;
                        this._OrderBy = orderBy;
                        this._QueryList = query;
                }
                private readonly bool _IsAll = true;
                public StringBuilder GenerateSql(out IDataParameter[] param)
                {
                        StringBuilder sql = new StringBuilder("select top 1 ", 500);
                        sql.AppendJoin(',', this._Columns);
                        sql.Append(" from (");
                        List<IDataParameter> list = new List<IDataParameter>();

                        sql.Append(this._QueryList[0].GenerateSql(out IDataParameter[] p));
                        list.AddRange(p);
                        string cen = " union all (";
                        if (!this._IsAll)
                        {
                                cen = " union (";
                        }
                        for (int i = 1; i < this._QueryList.Length; i++)
                        {
                                sql.Append(cen);
                                sql.Append(this._QueryList[i].GenerateSql(out p));
                                list.AddRange(p);
                                sql.Append(")");
                        }
                        sql.Append(") ");
                        if (this._OrderBy != null)
                        {
                                sql.Append(" order by ");
                                sql.Append(this._OrderBy);
                        }
                        param = list.ToArray();
                        return sql;
                }
        }
}
